<?php
// +----------------------------------------------------------------------
// | my
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\we\model;

use think\Model;

class WeFans extends Model
{

    
    /**
     * 获取微信配置信息，需要缓存
     */
    public function info($openid,$field=true){
      
      if (is_numeric($openid)){
        $map['id']=$openid;
      }else{
        $map['openid']=$openid;
      }
      $fans = $this->field($field)->where($map)->find();

      if(!$fans) return;
      //处理财务
      $cfo=model('we/WeFansCfo')->info($openid);
    
      $fans['score']=(isset($cfo['score'])?$cfo['score']:0);
      $fans['amount']=(isset($cfo['amount'])?$cfo['amount']:0);
  
      $printer=model('printer/PrinterFans')->info($openid,'balance');
      $fans['printer']=(isset($printer['balance'])?$printer['balance']:0);
     
      //如果是管理员，获取管理员信息
      if ($fans['admin']){
        $admin=model('admin/AdminUser')->info($fans['admin']);
        if ($admin){
          $admin['shop_title']=db('admin_shop')->where('id',$admin['shopid'])->value('title');
          $fans['admin_info']=$admin;
        }
      }

      //对旧数据进行转换

      
      return  $fans;
    }



    public function infoForFans($openid,$field=true){

      $fans=$this->info($openid,$field=true);
      if (!$fans) return false;
    
      $message="粉丝信息";
      $message.="\n粉丝ID：".$fans['id'];
      $message.="\n昵称：".$fans['nickname'];
      if($fans['amount'])$message.="\n余额：".$fans['amount'];
      if($fans['score'])$message.="\n积星：".$fans['score'];
      if($fans['printer'])$message.="\n打印余额：".$fans['printer'];

      $message.="\n--------------";
      $url=request()->domain().url('we/space/index',['openid'=>$fans['openid']]);
      $pay_url=request()->domain().url('we/space/amount',['openid'=>$fans['openid']]);
      $message.="\n".'<a href="'.$pay_url.'">会员充值</a>';
      $message.="\n".'<a href="'.$url.'">我的特权</a>';
      if($fans['admin']) {
        $message.="\n-------------";
        $message.="\n".$fans['admin_info']['name']."你是本店管理员:";
        $shop=model('admin/AdminShop')->info($fans['admin_info']['shopid']);
        $message.="\n分店:".$shop['title'];
        $message.="\n电话:".$fans['admin_info']['mobile'];
        $message.="\n--------------";
        $url=request()->domain().url('admin/space/index',['id'=>$fans['admin_info']['id'],'openid'=>$openid]);
        $message.="\n".'<a href="'.$url.'">管理面板</a>';
      }
     
      return  ['fans'=>$fans,'message'=>$message];
    }

    public function infoForFansByOrder($data){
     //todo 处理电话号码查询
    
      
     if (is_mobile($data['before'])){
        $fanss=$this->where('mobile',$data['before'])->select();
        if (!$fanss){ 
          $cfo=db('WeFansCfo')->where('mobile',$data['before'])->find();
          if ($cfo)return ['message'=>'该电话号码没有微信关注过我们，但是查到一张会员卡，余额'.$cfo['amount']];
          return ['message'=>'该电话号码下面没有粉丝'];
        }
        $message='该粉丝号下面有'.count($fanss).'个粉丝';
        foreach ($fanss as $key => $value) {
          $message.="\n".$value['id'].":".$value['nickname'];
        }
        return ['message'=>$message];
     }else{
        $fans = $this->infoForFans($data['before']);
        if (!$fans) return ['message'=>'粉丝不存在，请核对粉丝ID'];
        return ['message'=>$fans['message']]; //空尾巴查询
     }
     
     
    }

    //智能分析顾客分店
    public function SmartShopid($openid){
        //根据扫码获取
        $map['openid']=$openid;
        $map['status']=['egt',0];
        $map['shopid']=['neq',''];
        $scan=model('we/WeSceneScan')->where($map)->order('create_time desc')->limit(1)->find();
        if ($scan) return $scan['shopid'];
       
    }

    public function getAdmins($appid){
      $map['appid']=$appid;
      $map['admin']=['NEQ',''];
      $admins=$this->where($map)->cache(3600)->select();
      return  $admins;
    }

    public function getBosss($appid){
      $map['appid']=$appid;
      $map['boss']=1;
      $bosss=$this->field('openid,nickname')->where($map)->select();
      return  $bosss;
    }

    public function getFeedAdmins($appid){
      $map['appid']=$appid;
      $map['feed_notice']=1;
      $admins=$this->field('openid,nickname')->where($map)->select();
      return  $admins;
    }

    public function checkAdmin($openid){
     $fans=$this->info($openid);
     if (!$fans['admin']) {
      $url=request()->domain().url('admin/space/login',['openid'=>$fans['openid']]);
      $message='<a href="'.$url.'">点击这里登录</a>';
      return ['status'=>0,'text'=>'请输入手机号FA密码登录，或者'.$message];
     }else{
      $admin=model('admin/AdminUser')->info($fans['admin']);
      
      if ($admin['aid']==$fans['aid'])return $admin;
       return ['status'=>0,'text'=>'没有权限'];   
     }
     
    }




    public function editData($data){

        
      if (isset($data['id'])){
         $res = $this->allowField(true)->where('id',$data['id'])->update($data);
      }else{
          $res = $this->allowField(true)->data($data)->save();
      }
    
      return $res;
    }

    public function F($data) {
       
        //普通处理
        $first=substr($data['back'],0,1);
        $um=str_replace($first,"",$data['back']);
        

        if ($first=="A"){
            $hasUser = db('admin_user')->where(array('mobile' => $data['before'],'aid' =>$data['aid']))->find();

            if(empty($hasUser)) return ['message'=>'管理员不存在'];
            if(md5(md5($um) . config('data_auth_key'))!= $hasUser['password']) return ['message'=>'密码错误'];
            if(1 != $hasUser['status']) return ['message'=>'账号被禁用'];
           

            $res=db('WeFans')->where('openid',$data['openid'])->update(['admin'=>$hasUser['id']]);
            if ($res)  return ['message'=>$hasUser['name'].'登录成功'];
            return ['message'=>'不需要重复登录'];

        }


         //其他需要验证权限
        $admin=model('we/WeFans')->checkAdmin($data['openid']);
        if($admin['status']==0) return $admin['text'];

        //消费 (粉丝F1++100)
        if(strstr($data['back'],'+')){
           return $message=model('we/WeFansBuy')->buy($data);
        }

      //兼容手机老会员
        if (is_mobile($data['before']) and $first=="M"){
          $cfo=db('WeFansCfo')->where('mobile',$data['before'])->where('aid',$data['aid'])->find();
          if ($cfo){
            if($um>0){
                $res= db('WeFansCfo')->where('mobile',$data['before'])->where('aid',$data['aid'])->setInc('amount',$um);
            }else{
                $res= db('WeFansCfo')->where('mobile',$data['before'])->where('aid',$data['aid'])->setDec('amount',abs($um));
            }

           $log['aid']=$data['fans']['aid'];
           $log['appid']=$data['fans']['appid'];
           $log['shopid']=(isset($data['fans']['admin_info'])?$data['fans']['admin_info']['shopid']:'');
           $log['type']=0;
           $log['pay_type']=0;
           $log['mobile']=$data['before'];
           $log['admin']=(isset($data['admin'])?$data['admin']:'');
           $log['um']=$um;
           $log['balance']=($cfo['amount']+$um);
           $log['description']="手机号会员";
          
           $log_res=model('we/WeFansCfoLog')->editData($log); 
            if ($res>0)return ['message'=>'已经为该会员变更'.$data['back']."元，结余".($cfo['amount']+$um)];

          }else{
            return ['message'=>'该电话号码没有发现会员卡，请核实']; 
          }
         
        } 


        $fans=$this->info($data['before']);
        if (!$fans and $first<>'A')return ['message'=>$data['before'].'号粉丝不存在'];
       
        switch ( $first) {
          case 'M':
            return model('we/WeFansCfo')->cfoAmount($fans,$um,$data);
            break;
          case 'S':
            $callback=model('we/WeFansCfo')->cfoScore($fans,$um,$data);
            return $callback['message'];
            break;
          case 'C':

            $c_first=mb_substr($um,0,1);
            
            switch ($c_first) {
              case '卡':
                $card_id=str_replace($c_first,"",$um);
                if (!$card_id){
                  $cards=db('WeCard')->where('appid',$data['appid'])->where('status>0')->select();
                  $reply='卡券列表：';
                  foreach ($cards as $key => $card) {
                    $reply.="\n".$card['id']."号-".$card['fixed_begin_term'].'天-'.$card['title'];
                  }
                  return ['message'=>$reply];

                }else{
                  $card=model('we/weCard')->info($card_id);
                  $message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$card['card_id']]];
                }
                
                break;
              
              default:
               
                $message=['msgtype'=>'text','text'=>['content'=>$um]];
                break;
            }
            $error= custom_message($fans['openid'],$message);
            return ['message'=>!$error?'发送成功给'.$fans['nickname']:$error];
           break;
         
          }

          
     }

     public function downAvatar($fans,$w='250',$h='250'){
        $path="uploads/we/avatar";
        createFolder($path);
        $pic_name=$fans['openid'].'.jpg';
        $this_avatar_pic=$path.'/'.$pic_name;
        if (!file_exists($this_avatar_pic)) {
          get_file_from_net($fans['headimgurl'],$path,$pic_name);
          $image = \think\Image::open($this_avatar_pic);
          $image->thumb($w,$h,\think\Image::THUMB_CENTER)->save($this_avatar_pic);
        }
       
        return $this_avatar_pic;
    }

    public function paySuccess(){
       //标记打赏了多少钱
       
       $pay=session('pay');
       $fans=model('we/WeFans')->info($pay['data_id']);
       $data['nickname']='系统';
       $data['openid']=$fans['openid'];
       $res=model('we/WeFansCfo')->cfoAmount($fans,$pay['price'],$data,'微信支付自助充值');
      

    }


    
}